<!DOCTYPE html>
<html lang="zh_cn">
<head>
          <title>来玩魔王的咚</title>
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <meta charset="utf-8" />
        <!-- twitter card metadata -->
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="/images/mowang.png">
<meta name="twitter:site" content="">
<meta name="twitter:title" content="底层编程（unsafe包）">
<meta name="twitter:description" content="<p>unsafe包：Sizeof、Alignof和Offsetof，结构体内存对齐；unsafe.Pointer：查看浮点类型的位模式，修改结构体成员的值，不要把uintptr类型赋值给临时变量，reflect包返回的uintptr；深度相等示例：DeepEqual的不足，函数实现，支持循环引用，测试验证；注意事项</p>">
        <!-- OG Tags -->
<meta property="og:url" content="/gopl-low-level-programming.html"/>
<meta property="og:title" content="来玩魔王的咚 | 底层编程（unsafe包）" />
<meta property="og:description" content="<p>unsafe包：Sizeof、Alignof和Offsetof，结构体内存对齐；unsafe.Pointer：查看浮点类型的位模式，修改结构体成员的值，不要把uintptr类型赋值给临时变量，reflect包返回的uintptr；深度相等示例：DeepEqual的不足，函数实现，支持循环引用，测试验证；注意事项</p>" />
        <!-- favicon -->
        <link rel="icon" type="image/png" href="/images/mowang.png">
        <!-- moment.js for date formatting -->
        <script src="/theme/js/moment.js"></script>
        <!-- css -->
        <link rel="stylesheet" type="text/css" href="/theme/css/main.css" />
        <!-- 左边的menu，如果页面高度不够，就跟着滚动，否则文章分类显示不全 -->
        <link rel="stylesheet" type="text/css" href="/theme/css/mycss/menu.css" />
		<script>
			
                /*! grunt-grunticon Stylesheet Loader - v2.1.2 | https://github.com/filamentgroup/grunticon | (c) 2015 Scott Jehl, Filament Group, Inc. | MIT license. */
    
    (function(e){function t(t,n,r,o){"use strict";function a(){for(var e,n=0;u.length>n;n++)u[n].href&&u[n].href.indexOf(t)>-1&&(e=!0);e?i.media=r||"all":setTimeout(a)}var i=e.document.createElement("link"),l=n||e.document.getElementsByTagName("script")[0],u=e.document.styleSheets;return i.rel="stylesheet",i.href=t,i.media="only x",i.onload=o||null,l.parentNode.insertBefore(i,l),a(),i}var n=function(r,o){"use strict";if(r&&3===r.length){var a=e.navigator,i=e.Image,l=!(!document.createElementNS||!document.createElementNS("http://www.w3.org/2000/svg","svg").createSVGRect||!document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#Image","1.1")||e.opera&&-1===a.userAgent.indexOf("Chrome")||-1!==a.userAgent.indexOf("Series40")),u=new i;u.onerror=function(){n.method="png",n.href=r[2],t(r[2])},u.onload=function(){var e=1===u.width&&1===u.height,a=r[e&&l?0:e?1:2];n.method=e&&l?"svg":e?"datapng":"png",n.href=a,t(a,null,null,o)},u.src="",document.documentElement.className+=" grunticon"}};n.loadCSS=t,e.grunticon=n})(this);(function(e,t){"use strict";var n=t.document,r="grunticon:",o=function(e){if(n.attachEvent?"complete"===n.readyState:"loading"!==n.readyState)e();else{var t=!1;n.addEventListener("readystatechange",function(){t||(t=!0,e())},!1)}},a=function(e){return t.document.querySelector('link[href$="'+e+'"]')},c=function(e){var t,n,o,a,c,i,u={};if(t=e.sheet,!t)return u;n=t.cssRules?t.cssRules:t.rules;for(var l=0;n.length>l;l++)o=n[l].cssText,a=r+n[l].selectorText,c=o.split(");")[0].match(/US\-ASCII\,([^"']+)/),c&&c[1]&&(i=decodeURIComponent(c[1]),u[a]=i);return u},i=function(e){var t,o,a;o="data-grunticon-embed";for(var c in e)if(a=c.slice(r.length),t=n.querySelectorAll(a+"["+o+"]"),t.length)for(var i=0;t.length>i;i++)t[i].innerHTML=e[c],t[i].style.backgroundImage="none",t[i].removeAttribute(o);return t},u=function(t){"svg"===e.method&&o(function(){i(c(a(e.href))),"function"==typeof t&&t()})};e.embedIcons=i,e.getCSS=a,e.getIcons=c,e.ready=o,e.svgLoadedCallback=u,e.embedSVG=u})(grunticon,this);
                
                grunticon(["/theme/css/icons.data.svg.css", "/theme/css/icons.data.png.css", "/theme/css/icons.fallback.css"]);
            </script>
        <noscript><link href="/theme/css/icons.fallback.css" rel="stylesheet"></noscript>
        <!-- menu toggle javascript -->
        <script type="text/javascript">
            document.addEventListener("DOMContentLoaded", initMenu);
            
            function initMenu(){
                var menu = document.getElementById("menu");
                var menulink = document.getElementById("menu-link");
                menulink.addEventListener("click", function toggleMenu(){
                        window.event.preventDefault();
                        menulink.classList.toggle('active');
                        menu.classList.toggle('active');              
                    });
            };
        </script>
        <!-- 不蒜子 -->
        <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

    <meta name="description" content="<p>unsafe包：Sizeof、Alignof和Offsetof，结构体内存对齐；unsafe.Pointer：查看浮点类型的位模式，修改结构体成员的值，不要把uintptr类型赋值给临时变量，reflect包返回的uintptr；深度相等示例：DeepEqual的不足，函数实现，支持循环引用，测试验证；注意事项</p>" />

    <meta name="tags" content="gopl" />
  <!-- 替换部分base的样式，看文章时，要再宽一点，右边有很多空间可以撑开 -->
  <link rel="stylesheet" type="text/css" href="/theme/css/mycss/article.css" />

</head>
<body>
    <div role="banner" id="masthead">
        <header>
            <a href="/"><img src="/images/mowang.png" alt="McManus Logo"></a>
                <h1>来玩魔王的咚@骑士救兵</h1>
            <a href="#menu" id="menu-link">more stuff</a>
            <nav id="menu">
                <ul>
                        <li><a href="/tags">tags</a></li>
                            <li><a href="/category/cloud.html">Cloud</a></li>
                            <li><a href="/category/docker.html">Docker</a></li>
                            <li class="active"><a href="/category/go.html">Go</a></li>
                            <li><a href="/category/linux.html">Linux</a></li>
                            <li><a href="/category/python.html">Python</a></li>
                            <li><a href="/category/xue-xi-bi-ji.html">学习笔记</a></li>
                            <li><a href="/category/yun-wei-zi-dong-hua.html">运维自动化</a></li>
                </ul>
            </nav>
        </header>
    </div>
        <div class="page" role="main">
  <div class="article" role="article">
    <article>
        <footer>
            <a name="top"></a>
            <p>
              <time datetime=" 2020-08-18 14:00:00+08:00">
                <script>document.write(moment('2020-08-18 14:00:00+08:00').format('LL'));</script>
              </time>
              ~
              <time datetime=" 2020-08-18 14:00:00+08:00">
                <script>document.write(moment('2020-08-18 14:00:00+08:00').format('LL'));</script>
              </time>
            </p>
        </footer>
        <header>
          <h2>
            底层编程（unsafe包）
          </h2>
        </header>
      <div class="content">
         <div class="toc">
<ul>
<li><a href="#unsafesizeofalignof-he-offsetof">unsafe.Sizeof、Alignof 和 Offsetof</a><ul>
<li><a href="#nei-cun-dui-qi">内存对齐</a></li>
<li><a href="#ling-liang-ge-han-shu">另两个函数</a></li>
</ul>
</li>
<li><a href="#unsafepointer">unsafe.Pointer</a><ul>
<li><a href="#cha-kan-fu-dian-lei-xing-de-wei-mo-shi">查看浮点类型的位模式</a></li>
<li><a href="#xiu-gai-jie-gou-ti-cheng-yuan-de-zhi">修改结构体成员的值</a></li>
<li><a href="#bu-yao-ba-uintptr-lei-xing-fu-zhi-gei-lin-shi-bian-liang">不要把 uintptr 类型赋值给临时变量</a></li>
<li><a href="#reflect-bao-fan-hui-de-uintptr">reflect 包返回的 uintptr</a></li>
</ul>
</li>
<li><a href="#shi-li-shen-du-xiang-deng">示例：深度相等</a><ul>
<li><a href="#deepequal-de-bu-zu">DeepEqual 的不足</a></li>
<li><a href="#zi-ding-yi-bi-jiao-han-shu">自定义比较函数</a></li>
<li><a href="#zhi-chi-xun-huan-yin-yong">支持循环引用</a></li>
<li><a href="#ce-shi-yan-zheng">测试验证</a></li>
</ul>
</li>
<li><a href="#guan-yu-an-quan-de-zhu-yi-shi-xiang">关于安全的注意事项</a></li>
</ul>
</div>
<p>包 unsafe 广泛使用在和操作系统交互的低级包中, 例如 runtime、os、syscall、net 等，但是普通程序是不需要使用它的。  </p>
<h3 id="unsafesizeofalignof-he-offsetof"><a class="toclink" href="#unsafesizeofalignof-he-offsetof">unsafe.Sizeof、Alignof 和 Offsetof</a></h3>
<p>函数 unsafe.Sizeof 报告传递给它的参数在内存中占用的字节（Byte）长度（1Byte=8bit，1个字节是8位），参数可以是任意类型的表达式，但它不会对表达式进行求值。对 Sizeof 的调用会返回一个 uintptr 类型的常量表达式，所以返回的结果可以作为数组类型的长度大小，或者用作计算其他的常量：</p>
<div class="highlight"><pre><span></span><code><span class="nx">fmt</span><span class="p">.</span><span class="nx">Println</span><span class="p">(</span><span class="nx">unsafe</span><span class="p">.</span><span class="nx">Sizeof</span><span class="p">(</span><span class="nb">float64</span><span class="p">(</span><span class="mi">0</span><span class="p">)))</span><span class="w"> </span><span class="c1">// &quot;8&quot;</span><span class="w"></span>
<span class="nx">fmt</span><span class="p">.</span><span class="nx">Println</span><span class="p">(</span><span class="nx">unsafe</span><span class="p">.</span><span class="nx">Sizeof</span><span class="p">(</span><span class="nb">uint8</span><span class="p">(</span><span class="mi">0</span><span class="p">)))</span><span class="w"> </span><span class="c1">// &quot;1&quot;</span><span class="w"></span>
</code></pre></div>

<p>函数 Sizeof 仅报告每个数据结构固定部分的内存占用的字节长度。以字符串为例，报告的只是字符串对应的指针的字节长度，而不是字符串内容的长度：</p>
<div class="highlight"><pre><span></span><code><span class="kd">func</span><span class="w"> </span><span class="nx">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="kd">var</span><span class="w"> </span><span class="nx">x</span><span class="w"> </span><span class="kt">string</span><span class="w"></span>
<span class="w">    </span><span class="nx">x</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="s">&quot;a&quot;</span><span class="w"></span>
<span class="w">    </span><span class="nx">fmt</span><span class="p">.</span><span class="nx">Println</span><span class="p">(</span><span class="nx">unsafe</span><span class="p">.</span><span class="nx">Sizeof</span><span class="p">(</span><span class="nx">x</span><span class="p">),</span><span class="w"> </span><span class="nb">len</span><span class="p">(</span><span class="nx">x</span><span class="p">))</span><span class="w"> </span><span class="c1">// &quot;16 1&quot;</span><span class="w"></span>

<span class="w">    </span><span class="kd">var</span><span class="w"> </span><span class="nx">s</span><span class="w"> </span><span class="p">[]</span><span class="kt">string</span><span class="w"></span>
<span class="w">    </span><span class="k">for</span><span class="w"> </span><span class="nx">i</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="mi">0</span><span class="p">;</span><span class="w"> </span><span class="nx">i</span><span class="w"> </span><span class="p">&lt;</span><span class="w"> </span><span class="mi">10000</span><span class="p">;</span><span class="w"> </span><span class="nx">i</span><span class="o">++</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="nx">s</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="nb">append</span><span class="p">(</span><span class="nx">s</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;Hello&quot;</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"></span>
<span class="w">    </span><span class="nx">x</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="nx">strings</span><span class="p">.</span><span class="nx">Join</span><span class="p">(</span><span class="nx">s</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;, &quot;</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="nx">fmt</span><span class="p">.</span><span class="nx">Println</span><span class="p">(</span><span class="nx">unsafe</span><span class="p">.</span><span class="nx">Sizeof</span><span class="p">(</span><span class="nx">x</span><span class="p">),</span><span class="w"> </span><span class="nb">len</span><span class="p">(</span><span class="nx">x</span><span class="p">))</span><span class="w"> </span><span class="c1">// &quot;16 69998&quot;</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>
</code></pre></div>

<p>无论字符串多长，unsafe.Sizeof 返回的大小总是一样的。  </p>
<p>Go 语言中非聚合类型通常有一个固定的大小，尽管在不同工具链下生成的实际大小可能会有所不同。考虑到可移植性，引用类型或包含引用类型的大小都是1个字（word），转换为字节数，在32位系统上是4个字节，在64位系统上是8个字节。  </p>
<table>
<thead>
<tr>
<th>类型</th>
<th>大小</th>
</tr>
</thead>
<tbody>
<tr>
<td>bool</td>
<td>1个字节</td>
</tr>
<tr>
<td>intN, uintN, floatN, complexN</td>
<td>N/8个字节(例如float64是8个字节)</td>
</tr>
<tr>
<td>int, uint, uintptr</td>
<td>1个字</td>
</tr>
<tr>
<td>*T</td>
<td>1个字</td>
</tr>
<tr>
<td>string</td>
<td>2个字(data,len)</td>
</tr>
<tr>
<td>[]T</td>
<td>3个字(data,len,cap)</td>
</tr>
<tr>
<td>map</td>
<td>1个字</td>
</tr>
<tr>
<td>func</td>
<td>1个字</td>
</tr>
<tr>
<td>chan</td>
<td>1个字</td>
</tr>
<tr>
<td>interface</td>
<td>2个字(type,value)</td>
</tr>
</tbody>
</table>
<h4 id="nei-cun-dui-qi"><a class="toclink" href="#nei-cun-dui-qi">内存对齐</a></h4>
<p>在类型的值在内存中<strong>对齐</strong>的情况下，计算机的加载或者写入会很高效。例如，int16的大小是2字节地址应该是偶数，rune类型的大小是4字节地址应该是4的倍数，float64、uint64 或 64位指针的大小是8字节地址应该是8的倍数。对于更大倍数的地址对齐是不需要的，即使是complex128等较大的数据类型最多也只是8字节对齐。  </p>
<h5 id="jie-gou-ti-de-nei-cun-dui-qi"><a class="toclink" href="#jie-gou-ti-de-nei-cun-dui-qi">结构体的内存对齐</a></h5>
<p>因此，聚合类型（结构体或数组）的值的长度至少是它的成员或元素的长度之和。并且由于“内存间隙”的存在，可能还会更大一些。内存空位是由编译器添加的未使用的内存地址，用来确保连续的成员或元素相对于结构体或数组的起始地址是对齐的。<br>
语言规范不要求结构体成员声明的顺序对应内存中的布局顺序，所以在理论上，编译器可以自由安排，但实际上并没有这么做。如果结构体成员的类型是不同的，不同的排列顺序可能使得结构体占用的内存不同。比如下面的三个结构体拥有相同的成员，但是第一种写法比其他两个定义需要占更多内存：</p>
<div class="highlight"><pre><span></span><code><span class="w">                                              </span><span class="c1">// 64-bit    32-bit</span><span class="w"></span>
<span class="kd">struct</span><span class="p">{</span><span class="w"> </span><span class="kt">bool</span><span class="p">;</span><span class="w"> </span><span class="kt">float64</span><span class="p">;</span><span class="w"> </span><span class="kt">int16</span><span class="w"> </span><span class="p">}</span><span class="w"> </span><span class="c1">// 3 words 4words</span><span class="w"></span>
<span class="kd">struct</span><span class="p">{</span><span class="w"> </span><span class="kt">float64</span><span class="p">;</span><span class="w"> </span><span class="kt">int16</span><span class="p">;</span><span class="w"> </span><span class="kt">bool</span><span class="w"> </span><span class="p">}</span><span class="w"> </span><span class="c1">// 2 words 3words</span><span class="w"></span>
<span class="kd">struct</span><span class="p">{</span><span class="w"> </span><span class="kt">bool</span><span class="p">;</span><span class="w"> </span><span class="kt">int16</span><span class="p">;</span><span class="w"> </span><span class="kt">float64</span><span class="w"> </span><span class="p">}</span><span class="w"> </span><span class="c1">// 2 words 3words</span><span class="w"></span>
</code></pre></div>

<p>对齐算法太底层了（虽然貌似也没有特别难），但确实不值得担心每个结构体的内存布局，不过高效排列可以使数据结构更加紧凑。一个容易掌握的建议是，将相同类型的成员定义在一起有可能更节约内存空间。  </p>
<h4 id="ling-liang-ge-han-shu"><a class="toclink" href="#ling-liang-ge-han-shu">另两个函数</a></h4>
<p>函数 unsafe.Alignof 报告它参数类型所要求的对齐方式。和 Sizeof 一样，它的参数可以是任意类型的表达式，并且返回一个常量。通常情况下布尔和数值类型对齐到它们的长度(最多8个字节), 其它的类型则按字（word）对齐。  </p>
<p>函数 unsafe.Offsetof，参数必须是结构体 x 的一个字段 x.f。函数返回 f 相对于结构体 x 起始地址的偏移值，如果有内存空位，也会计算在内。  </p>
<p>虽然这几个函数在不安全的unsafe包里，但是这几个函数是安全的，特别在需要优化内存空间时它们返回的结果对于理解原生的内存布局很有帮助。  </p>
<h3 id="unsafepointer"><a class="toclink" href="#unsafepointer">unsafe.Pointer</a></h3>
<p>很多指针类型都写做 *T，意思是“一个指向T类型变量的指针”。unsafe.Pointer 类型是一种特殊类型的指针，它可以存储任何变量的地址。这里不可以直接通过 *P 来获取 unsafe.Pointer 指针指向的那个变量的值，因为并不知道变量的具体类型。和普通的指针一样，unsafe.Pointer 类型的指针是可比较的并且可以和 nil 做比较，nil 是指针类型的零值。  </p>
<h4 id="cha-kan-fu-dian-lei-xing-de-wei-mo-shi"><a class="toclink" href="#cha-kan-fu-dian-lei-xing-de-wei-mo-shi">查看浮点类型的位模式</a></h4>
<p>一个普通的指针 *T 可以转换为 unsafe.Pointer 类型的指针，并且一个 unsafe.Pointer 类型的指针也可以转换回普通的指针，被转换回普通指针的类型不需要和原来的 *T 类型相同。这里有一个简单的应用场景，先将 *float64 类型指针转化为 *uint64 然后再把内存中的值打印出来。这时候就是按照 uint64 类型来把值打印出来，这样就可以看到浮点类型的变量在内存中的位模式：</p>
<div class="highlight"><pre><span></span><code><span class="kd">func</span><span class="w"> </span><span class="nx">Float64bits</span><span class="p">(</span><span class="nx">f</span><span class="w"> </span><span class="kt">float64</span><span class="p">)</span><span class="w"> </span><span class="kt">uint64</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="o">*</span><span class="p">(</span><span class="o">*</span><span class="kt">uint64</span><span class="p">)(</span><span class="nx">unsafe</span><span class="p">.</span><span class="nx">Pointer</span><span class="p">(</span><span class="o">&amp;</span><span class="nx">f</span><span class="p">))</span><span class="w"> </span><span class="p">}</span><span class="w"></span>

<span class="kd">func</span><span class="w"> </span><span class="nx">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="nx">fmt</span><span class="p">.</span><span class="nx">Printf</span><span class="p">(</span><span class="s">&quot;%#016x\n&quot;</span><span class="p">,</span><span class="w"> </span><span class="nx">Float64bits</span><span class="p">(</span><span class="mf">1.0</span><span class="p">))</span><span class="w"> </span><span class="c1">// &quot;0x3ff0000000000000&quot;</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>
</code></pre></div>

<h4 id="xiu-gai-jie-gou-ti-cheng-yuan-de-zhi"><a class="toclink" href="#xiu-gai-jie-gou-ti-cheng-yuan-de-zhi">修改结构体成员的值</a></h4>
<p>很多 unsafe.Pointer 类型的值都是从普通指针到原始内存地址以及再从内存地址到普通指针进行转换的中间值。下面的例子获取变量 x 的地址，然后加上其成员 b 的地址偏移量，并将结果转换为 *int16 指针类型，接着通过这个指针更新 x.b 的值：</p>
<div class="highlight"><pre><span></span><code><span class="kd">var</span><span class="w"> </span><span class="nx">x</span><span class="w"> </span><span class="kd">struct</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="nx">a</span><span class="w"> </span><span class="kt">bool</span><span class="w"></span>
<span class="w">    </span><span class="nx">b</span><span class="w"> </span><span class="kt">int16</span><span class="w"></span>
<span class="w">    </span><span class="nx">c</span><span class="w"> </span><span class="p">[]</span><span class="kt">int</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>

<span class="kd">func</span><span class="w"> </span><span class="nx">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="c1">// 等价于 pb := &amp;x.b ，但是这里是通过结构体的地址加上字段的偏移量计算后获取到的</span><span class="w"></span>
<span class="w">    </span><span class="nx">pb</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="p">(</span><span class="o">*</span><span class="kt">int16</span><span class="p">)(</span><span class="nx">unsafe</span><span class="p">.</span><span class="nx">Pointer</span><span class="p">(</span><span class="nb">uintptr</span><span class="p">(</span><span class="nx">unsafe</span><span class="p">.</span><span class="nx">Pointer</span><span class="p">(</span><span class="o">&amp;</span><span class="nx">x</span><span class="p">))</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="nx">unsafe</span><span class="p">.</span><span class="nx">Offsetof</span><span class="p">(</span><span class="nx">x</span><span class="p">.</span><span class="nx">b</span><span class="p">)))</span><span class="w"></span>
<span class="w">    </span><span class="o">*</span><span class="nx">pb</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="mi">42</span><span class="w"></span>
<span class="w">    </span><span class="nx">fmt</span><span class="p">.</span><span class="nx">Println</span><span class="p">(</span><span class="nx">x</span><span class="p">.</span><span class="nx">b</span><span class="p">)</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>
</code></pre></div>

<p>这里首先获取到结构体的地址，然后是成员的偏移量，相加后就是这个成员的内存地址。因为这里知道该地址指向的数据类型，所以直接用一个类型转换就获取到了成员 b 也就是 *int16 的指针地址。既然拿到指针类型了，就可以修改该指针指向的变量的值了。<br>
这种方法不要随意使用。  </p>
<h4 id="bu-yao-ba-uintptr-lei-xing-fu-zhi-gei-lin-shi-bian-liang"><a class="toclink" href="#bu-yao-ba-uintptr-lei-xing-fu-zhi-gei-lin-shi-bian-liang">不要把 uintptr 类型赋值给临时变量</a></h4>
<p>下面这段代码看似和上面的一样的，引入了一个临时变量 tmp，让把原来的一行拆成了两行，这里的 tmp 是 uintptr 类型。这种引入 uintptr 类型的临时变量，破坏原来整行代码的用法是错误的：</p>
<div class="highlight"><pre><span></span><code><span class="kd">func</span><span class="w"> </span><span class="nx">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="nx">tmp</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nb">uintptr</span><span class="p">(</span><span class="nx">unsafe</span><span class="p">.</span><span class="nx">Pointer</span><span class="p">(</span><span class="o">&amp;</span><span class="nx">x</span><span class="p">))</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="nx">unsafe</span><span class="p">.</span><span class="nx">Offsetof</span><span class="p">(</span><span class="nx">x</span><span class="p">.</span><span class="nx">b</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="nx">pb</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="p">(</span><span class="o">*</span><span class="kt">int64</span><span class="p">)(</span><span class="nx">unsafe</span><span class="p">.</span><span class="nx">Pointer</span><span class="p">(</span><span class="nx">tmp</span><span class="p">))</span><span class="w"></span>
<span class="w">    </span><span class="o">*</span><span class="nx">pb</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="mi">42</span><span class="w"></span>
<span class="w">    </span><span class="nx">fmt</span><span class="p">.</span><span class="nx">Println</span><span class="p">(</span><span class="nx">x</span><span class="p">.</span><span class="nx">b</span><span class="p">)</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>
</code></pre></div>

<p>原因很微妙。一些垃圾回收器会把内存中变量移来移去以减少内存碎片等问题。这种类型的垃圾回收器称为<strong>移动GC</strong>。当一个变量在内存中移动后，所有保存该变量旧地址的指针必须同时被更新为变量移动后的新地址。从垃圾回收器的角度看，unsafe.Pointer 是一个变量指针，当变量移动后它的值也会被更新。而 uintptr 仅仅是一个数值，在垃圾回收的时候这个值是不会变的。  </p>
<p>类似的错误用法还有像下面这样：</p>
<div class="highlight"><pre><span></span><code><span class="nx">pT</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nb">uintptr</span><span class="p">(</span><span class="nx">unsafe</span><span class="p">.</span><span class="nx">Pointer</span><span class="p">(</span><span class="nb">new</span><span class="p">(</span><span class="nx">T</span><span class="p">)))</span><span class="w"> </span><span class="c1">// 提示: 错误!</span><span class="w"></span>
</code></pre></div>

<p>当垃圾回收器将会在语句执行结束后回收内存，在这之后，pT存储的是变量的旧地址，而这个时候这个地址对应的已经不是那个变量了。  </p>
<p>目前Go语言还没有使用移动GC，所以上面的错误用法很多时候是可以正确运行的（<em>运行了几次，都没有出错</em>）。但是还是存在其他移动变量的场景。<br>
这样的代码能够通过编译并运行，编译器不会报错，不过会给一个提示性的错误信息：</p>
<div class="highlight"><pre><span></span><code>possible misuse of unsafe.Pointer
</code></pre></div>

<p>所以还是可以在编译的时候发现的。这里强烈建议遵守最小可用原则，不要使用任何包含变量地址的 uintptr 类型的变量，并减少不必要的 unsafe.Pointer 类型到 uintptr 类型的转换。像本小节第一个例子里那样，转换为 uintptr 类型，最终在转换回 unsafe.Pointer 类型的操作，都要在一条语句中完成。  </p>
<h4 id="reflect-bao-fan-hui-de-uintptr"><a class="toclink" href="#reflect-bao-fan-hui-de-uintptr">reflect 包返回的 uintptr</a></h4>
<p>当调用一个库函数，并且返回的是 uintptr 类型地址时，比如下面的 reflect 包中的几个函数。这些结果应该立刻转换为 unsafe.Pointer 来确保它们在接下来代码中能够始终指向原来的变量：</p>
<div class="highlight"><pre><span></span><code><span class="kn">package</span><span class="w"> </span><span class="nx">reflect</span><span class="w"></span>

<span class="kd">func</span><span class="w"> </span><span class="p">(</span><span class="nx">Value</span><span class="p">)</span><span class="w"> </span><span class="nx">Pointer</span><span class="p">()</span><span class="w"> </span><span class="kt">uintptr</span><span class="w"></span>
<span class="kd">func</span><span class="w"> </span><span class="p">(</span><span class="nx">Value</span><span class="p">)</span><span class="w"> </span><span class="nx">UnsafeAddr</span><span class="p">()</span><span class="w"> </span><span class="kt">uintptr</span><span class="w"></span>
<span class="kd">func</span><span class="w"> </span><span class="p">(</span><span class="nx">Value</span><span class="p">)</span><span class="w"> </span><span class="nx">InterfaceData</span><span class="p">()</span><span class="w"> </span><span class="p">[</span><span class="mi">2</span><span class="p">]</span><span class="kt">uintptr</span><span class="w"> </span><span class="c1">// (index 1)</span><span class="w"></span>
</code></pre></div>

<p>一般的函数尽量不要返回 uintptr 类型，可能也就反射这类底层编程的包有这种情况。<br>
下一节的示例中会用到 reflect.UnsafeAddr 函数，示例中立刻在同一行代码中就把返回值转成了 nsafe.Pointer 类型。  </p>
<h3 id="shi-li-shen-du-xiang-deng"><a class="toclink" href="#shi-li-shen-du-xiang-deng">示例：深度相等</a></h3>
<p>这篇要解决反射章节第一个例子 dispaly 中没有处理的循环引用的问题。这里需要使用 unsafe.Pointer 类型来保证地址可以始终指向最初的那个变量。  </p>
<p>reflect 包中的 DeepEqual 函数用来报告两个变量的值是否深度相等。DeepEqual 函数的基本类型使用内置的 == 操作符进行比较。对于组合类型，它逐层深入比较相应的元素。因为这个函数适合于任意的一对变量值的比较，甚至是那些无法通过 == 来比较的值，所以在一些测试代码中广泛地使用这个函数。下面的代码就是用 DeepEqual 来比较两个 []string 类型的值：</p>
<div class="highlight"><pre><span></span><code><span class="kd">func</span><span class="w"> </span><span class="nx">TestSplit</span><span class="p">(</span><span class="nx">t</span><span class="w"> </span><span class="o">*</span><span class="nx">testing</span><span class="p">.</span><span class="nx">T</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="nx">got</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">strings</span><span class="p">.</span><span class="nx">Split</span><span class="p">(</span><span class="s">&quot;a:b:c&quot;</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;:&quot;</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="nx">want</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="p">[]</span><span class="kt">string</span><span class="p">{</span><span class="s">&quot;a&quot;</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;b&quot;</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;c&quot;</span><span class="p">}</span><span class="w"></span>
<span class="w">    </span><span class="k">if</span><span class="w"> </span><span class="p">!</span><span class="nx">reflect</span><span class="p">.</span><span class="nx">DeepEqual</span><span class="p">(</span><span class="nx">got</span><span class="p">,</span><span class="w"> </span><span class="nx">want</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="cm">/* ... */</span><span class="w"> </span><span class="p">}</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>
</code></pre></div>

<h4 id="deepequal-de-bu-zu"><a class="toclink" href="#deepequal-de-bu-zu">DeepEqual 的不足</a></h4>
<p>虽然 DeepEqual 很方便，可以支持任意的数据类型，但是它的不足是判断过于武断。例如，一个值为 nil 的 map 和一个值不为 nil 的空 map 会判断为不相等，一个值为 nil 的切片和不为 nil 的空切片同样也会判断为不相等：</p>
<div class="highlight"><pre><span></span><code><span class="kd">var</span><span class="w"> </span><span class="nx">c</span><span class="p">,</span><span class="w"> </span><span class="nx">d</span><span class="w"> </span><span class="kd">map</span><span class="p">[</span><span class="kt">string</span><span class="p">]</span><span class="kt">int</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="kc">nil</span><span class="p">,</span><span class="w"> </span><span class="nb">make</span><span class="p">(</span><span class="kd">map</span><span class="p">[</span><span class="kt">string</span><span class="p">]</span><span class="kt">int</span><span class="p">)</span><span class="w"></span>
<span class="nx">fmt</span><span class="p">.</span><span class="nx">Println</span><span class="p">(</span><span class="nx">reflect</span><span class="p">.</span><span class="nx">DeepEqual</span><span class="p">(</span><span class="nx">c</span><span class="p">,</span><span class="w"> </span><span class="nx">d</span><span class="p">))</span><span class="w"> </span><span class="c1">// &quot;false&quot;</span><span class="w"></span>

<span class="kd">var</span><span class="w"> </span><span class="nx">a</span><span class="p">,</span><span class="w"> </span><span class="nx">b</span><span class="w"> </span><span class="p">[]</span><span class="kt">string</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="kc">nil</span><span class="p">,</span><span class="w"> </span><span class="p">[]</span><span class="kt">string</span><span class="p">{}</span><span class="w"></span>
<span class="nx">fmt</span><span class="p">.</span><span class="nx">Println</span><span class="p">(</span><span class="nx">reflect</span><span class="p">.</span><span class="nx">DeepEqual</span><span class="p">(</span><span class="nx">a</span><span class="p">,</span><span class="w"> </span><span class="nx">b</span><span class="p">))</span><span class="w"> </span><span class="c1">// &quot;false&quot;</span><span class="w"></span>
</code></pre></div>

<h4 id="zi-ding-yi-bi-jiao-han-shu"><a class="toclink" href="#zi-ding-yi-bi-jiao-han-shu">自定义比较函数</a></h4>
<p>所以，接下来要自己定义一个 Equal 函数。和 DeepEqual 类似，但是可以把一个值为 nil 的切片或 map 和一个值不为 nil 的空切片或 map 判断为相等。对参数的基本递归检查可以通过反射来实现。需要定义一个未导出的函数 equal 用来进行递归检查，隐藏反射的细节。参数 seen 是为了检查循环引用，并且因为要递归所以作为参数进行传递。对于每对要进行比较的值 x 和 y，equal 函数检查两者是否合法（IsValid）以及它们是否具有相同的类型（Type）。函数的结果通过 switch 的 case 语句返回，在 case 中比较两个相同类型的值：</p>
<div class="highlight"><pre><span></span><code><span class="kn">package</span><span class="w"> </span><span class="nx">equal</span><span class="w"></span>

<span class="kn">import</span><span class="w"> </span><span class="p">(</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;reflect&quot;</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;unsafe&quot;</span><span class="w"></span>
<span class="p">)</span><span class="w"></span>

<span class="kd">func</span><span class="w"> </span><span class="nx">equal</span><span class="p">(</span><span class="nx">x</span><span class="p">,</span><span class="w"> </span><span class="nx">y</span><span class="w"> </span><span class="nx">reflect</span><span class="p">.</span><span class="nx">Value</span><span class="p">,</span><span class="w"> </span><span class="nx">seen</span><span class="w"> </span><span class="kd">map</span><span class="p">[</span><span class="nx">comparison</span><span class="p">]</span><span class="kt">bool</span><span class="p">)</span><span class="w"> </span><span class="kt">bool</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="k">if</span><span class="w"> </span><span class="p">!</span><span class="nx">x</span><span class="p">.</span><span class="nx">IsValid</span><span class="p">()</span><span class="w"> </span><span class="o">||</span><span class="w"> </span><span class="p">!</span><span class="nx">y</span><span class="p">.</span><span class="nx">IsValid</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="k">return</span><span class="w"> </span><span class="nx">x</span><span class="p">.</span><span class="nx">IsValid</span><span class="p">()</span><span class="w"> </span><span class="o">==</span><span class="w"> </span><span class="nx">y</span><span class="p">.</span><span class="nx">IsValid</span><span class="p">()</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"></span>
<span class="w">    </span><span class="k">if</span><span class="w"> </span><span class="nx">x</span><span class="p">.</span><span class="nx">Type</span><span class="p">()</span><span class="w"> </span><span class="o">!=</span><span class="w"> </span><span class="nx">y</span><span class="p">.</span><span class="nx">Type</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="k">return</span><span class="w"> </span><span class="kc">false</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"></span>

<span class="w">    </span><span class="c1">// 循环检查</span><span class="w"></span>
<span class="w">    </span><span class="k">if</span><span class="w"> </span><span class="nx">x</span><span class="p">.</span><span class="nx">CanAddr</span><span class="p">()</span><span class="w"> </span><span class="o">&amp;&amp;</span><span class="w"> </span><span class="nx">y</span><span class="p">.</span><span class="nx">CanAddr</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="nx">xptr</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">unsafe</span><span class="p">.</span><span class="nx">Pointer</span><span class="p">(</span><span class="nx">x</span><span class="p">.</span><span class="nx">UnsafeAddr</span><span class="p">())</span><span class="w"> </span><span class="c1">// 获取变量的地址的数值，用于比较是不是相同的引用</span><span class="w"></span>
<span class="w">        </span><span class="nx">yptr</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">unsafe</span><span class="p">.</span><span class="nx">Pointer</span><span class="p">(</span><span class="nx">y</span><span class="p">.</span><span class="nx">UnsafeAddr</span><span class="p">())</span><span class="w"></span>
<span class="w">        </span><span class="k">if</span><span class="w"> </span><span class="nx">xptr</span><span class="w"> </span><span class="o">==</span><span class="w"> </span><span class="nx">yptr</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">            </span><span class="k">return</span><span class="w"> </span><span class="kc">true</span><span class="w"> </span><span class="c1">// 相同的引用</span><span class="w"></span>
<span class="w">        </span><span class="p">}</span><span class="w"></span>
<span class="w">        </span><span class="nx">c</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">comparison</span><span class="p">{</span><span class="nx">xptr</span><span class="p">,</span><span class="w"> </span><span class="nx">yptr</span><span class="p">,</span><span class="w"> </span><span class="nx">x</span><span class="p">.</span><span class="nx">Type</span><span class="p">()}</span><span class="w"></span>
<span class="w">        </span><span class="k">if</span><span class="w"> </span><span class="nx">seen</span><span class="p">[</span><span class="nx">c</span><span class="p">]</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">            </span><span class="k">return</span><span class="w"> </span><span class="kc">true</span><span class="w"> </span><span class="c1">// seen map 里已经存在的元素，表示已经比较过了</span><span class="w"></span>
<span class="w">        </span><span class="p">}</span><span class="w"></span>
<span class="w">        </span><span class="nx">seen</span><span class="p">[</span><span class="nx">c</span><span class="p">]</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="kc">true</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"></span>

<span class="w">    </span><span class="k">switch</span><span class="w"> </span><span class="nx">x</span><span class="p">.</span><span class="nx">Kind</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="k">case</span><span class="w"> </span><span class="nx">reflect</span><span class="p">.</span><span class="nx">Bool</span><span class="p">:</span><span class="w"></span>
<span class="w">        </span><span class="k">return</span><span class="w"> </span><span class="nx">x</span><span class="p">.</span><span class="nx">Bool</span><span class="p">()</span><span class="w"> </span><span class="o">==</span><span class="w"> </span><span class="nx">y</span><span class="p">.</span><span class="nx">Bool</span><span class="p">()</span><span class="w"></span>
<span class="w">    </span><span class="k">case</span><span class="w"> </span><span class="nx">reflect</span><span class="p">.</span><span class="nx">String</span><span class="p">:</span><span class="w"></span>
<span class="w">        </span><span class="k">return</span><span class="w"> </span><span class="nx">x</span><span class="p">.</span><span class="nx">String</span><span class="p">()</span><span class="w"> </span><span class="o">==</span><span class="w"> </span><span class="nx">y</span><span class="p">.</span><span class="nx">String</span><span class="p">()</span><span class="w"></span>

<span class="w">    </span><span class="c1">// 各种数值类型</span><span class="w"></span>
<span class="w">    </span><span class="k">case</span><span class="w"> </span><span class="nx">reflect</span><span class="p">.</span><span class="nx">Int</span><span class="p">,</span><span class="w"> </span><span class="nx">reflect</span><span class="p">.</span><span class="nx">Int8</span><span class="p">,</span><span class="w"> </span><span class="nx">reflect</span><span class="p">.</span><span class="nx">Int16</span><span class="p">,</span><span class="w"> </span><span class="nx">reflect</span><span class="p">.</span><span class="nx">Int32</span><span class="p">,</span><span class="w"></span>
<span class="w">        </span><span class="nx">reflect</span><span class="p">.</span><span class="nx">Int64</span><span class="p">:</span><span class="w"></span>
<span class="w">        </span><span class="k">return</span><span class="w"> </span><span class="nx">x</span><span class="p">.</span><span class="nx">Int</span><span class="p">()</span><span class="w"> </span><span class="o">==</span><span class="w"> </span><span class="nx">y</span><span class="p">.</span><span class="nx">Int</span><span class="p">()</span><span class="w"></span>
<span class="w">    </span><span class="k">case</span><span class="w"> </span><span class="nx">reflect</span><span class="p">.</span><span class="nx">Uint</span><span class="p">,</span><span class="w"> </span><span class="nx">reflect</span><span class="p">.</span><span class="nx">Uint8</span><span class="p">,</span><span class="w"> </span><span class="nx">reflect</span><span class="p">.</span><span class="nx">Uint16</span><span class="p">,</span><span class="w"> </span><span class="nx">reflect</span><span class="p">.</span><span class="nx">Uint32</span><span class="p">,</span><span class="w"></span>
<span class="w">        </span><span class="nx">reflect</span><span class="p">.</span><span class="nx">Uint64</span><span class="p">,</span><span class="w"> </span><span class="nx">reflect</span><span class="p">.</span><span class="nx">Uintptr</span><span class="p">:</span><span class="w"></span>
<span class="w">        </span><span class="k">return</span><span class="w"> </span><span class="nx">x</span><span class="p">.</span><span class="nx">Uint</span><span class="p">()</span><span class="w"> </span><span class="o">==</span><span class="w"> </span><span class="nx">y</span><span class="p">.</span><span class="nx">Uint</span><span class="p">()</span><span class="w"></span>
<span class="w">    </span><span class="k">case</span><span class="w"> </span><span class="nx">reflect</span><span class="p">.</span><span class="nx">Float32</span><span class="p">,</span><span class="w"> </span><span class="nx">reflect</span><span class="p">.</span><span class="nx">Float64</span><span class="p">:</span><span class="w"></span>
<span class="w">        </span><span class="k">return</span><span class="w"> </span><span class="nx">x</span><span class="p">.</span><span class="nx">Float</span><span class="p">()</span><span class="w"> </span><span class="o">==</span><span class="w"> </span><span class="nx">y</span><span class="p">.</span><span class="nx">Float</span><span class="p">()</span><span class="w"></span>
<span class="w">    </span><span class="k">case</span><span class="w"> </span><span class="nx">reflect</span><span class="p">.</span><span class="nx">Complex64</span><span class="p">,</span><span class="w"> </span><span class="nx">reflect</span><span class="p">.</span><span class="nx">Complex128</span><span class="p">:</span><span class="w"></span>
<span class="w">        </span><span class="k">return</span><span class="w"> </span><span class="nx">x</span><span class="p">.</span><span class="nx">Complex</span><span class="p">()</span><span class="w"> </span><span class="o">==</span><span class="w"> </span><span class="nx">y</span><span class="p">.</span><span class="nx">Complex</span><span class="p">()</span><span class="w"></span>

<span class="w">    </span><span class="k">case</span><span class="w"> </span><span class="nx">reflect</span><span class="p">.</span><span class="nx">Chan</span><span class="p">,</span><span class="w"> </span><span class="nx">reflect</span><span class="p">.</span><span class="nx">UnsafePointer</span><span class="p">,</span><span class="w"> </span><span class="nx">reflect</span><span class="p">.</span><span class="nx">Func</span><span class="p">:</span><span class="w"></span>
<span class="w">        </span><span class="k">return</span><span class="w"> </span><span class="nx">x</span><span class="p">.</span><span class="nx">Pointer</span><span class="p">()</span><span class="w"> </span><span class="o">==</span><span class="w"> </span><span class="nx">y</span><span class="p">.</span><span class="nx">Pointer</span><span class="p">()</span><span class="w"></span>

<span class="w">    </span><span class="k">case</span><span class="w"> </span><span class="nx">reflect</span><span class="p">.</span><span class="nx">Ptr</span><span class="p">,</span><span class="w"> </span><span class="nx">reflect</span><span class="p">.</span><span class="nx">Interface</span><span class="p">:</span><span class="w"></span>
<span class="w">        </span><span class="k">return</span><span class="w"> </span><span class="nx">equal</span><span class="p">(</span><span class="nx">x</span><span class="p">.</span><span class="nx">Elem</span><span class="p">(),</span><span class="w"> </span><span class="nx">y</span><span class="p">.</span><span class="nx">Elem</span><span class="p">(),</span><span class="w"> </span><span class="nx">seen</span><span class="p">)</span><span class="w"></span>

<span class="w">    </span><span class="k">case</span><span class="w"> </span><span class="nx">reflect</span><span class="p">.</span><span class="nx">Array</span><span class="p">,</span><span class="w"> </span><span class="nx">reflect</span><span class="p">.</span><span class="nx">Slice</span><span class="p">:</span><span class="w"></span>
<span class="w">        </span><span class="k">if</span><span class="w"> </span><span class="nx">x</span><span class="p">.</span><span class="nx">Len</span><span class="p">()</span><span class="w"> </span><span class="o">!=</span><span class="w"> </span><span class="nx">y</span><span class="p">.</span><span class="nx">Len</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">            </span><span class="k">return</span><span class="w"> </span><span class="kc">false</span><span class="w"></span>
<span class="w">        </span><span class="p">}</span><span class="w"></span>
<span class="w">        </span><span class="k">for</span><span class="w"> </span><span class="nx">i</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="mi">0</span><span class="p">;</span><span class="w"> </span><span class="nx">i</span><span class="w"> </span><span class="p">&lt;</span><span class="w"> </span><span class="nx">x</span><span class="p">.</span><span class="nx">Len</span><span class="p">();</span><span class="w"> </span><span class="nx">i</span><span class="o">++</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">            </span><span class="k">if</span><span class="w"> </span><span class="p">!</span><span class="nx">equal</span><span class="p">(</span><span class="nx">x</span><span class="p">.</span><span class="nx">Index</span><span class="p">(</span><span class="nx">i</span><span class="p">),</span><span class="w"> </span><span class="nx">y</span><span class="p">.</span><span class="nx">Index</span><span class="p">(</span><span class="nx">i</span><span class="p">),</span><span class="w"> </span><span class="nx">seen</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">                </span><span class="k">return</span><span class="w"> </span><span class="kc">false</span><span class="w"></span>
<span class="w">            </span><span class="p">}</span><span class="w"></span>
<span class="w">        </span><span class="p">}</span><span class="w"></span>
<span class="w">        </span><span class="k">return</span><span class="w"> </span><span class="kc">true</span><span class="w"></span>

<span class="w">    </span><span class="k">case</span><span class="w"> </span><span class="nx">reflect</span><span class="p">.</span><span class="nx">Struct</span><span class="p">:</span><span class="w"></span>
<span class="w">        </span><span class="k">for</span><span class="w"> </span><span class="nx">i</span><span class="p">,</span><span class="w"> </span><span class="nx">n</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="mi">0</span><span class="p">,</span><span class="w"> </span><span class="nx">x</span><span class="p">.</span><span class="nx">NumField</span><span class="p">();</span><span class="w"> </span><span class="nx">i</span><span class="w"> </span><span class="p">&lt;</span><span class="w"> </span><span class="nx">n</span><span class="p">;</span><span class="w"> </span><span class="nx">i</span><span class="o">++</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">            </span><span class="k">if</span><span class="w"> </span><span class="p">!</span><span class="nx">equal</span><span class="p">(</span><span class="nx">x</span><span class="p">.</span><span class="nx">Field</span><span class="p">(</span><span class="nx">i</span><span class="p">),</span><span class="w"> </span><span class="nx">y</span><span class="p">.</span><span class="nx">Field</span><span class="p">(</span><span class="nx">i</span><span class="p">),</span><span class="w"> </span><span class="nx">seen</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">                </span><span class="k">return</span><span class="w"> </span><span class="kc">false</span><span class="w"></span>
<span class="w">            </span><span class="p">}</span><span class="w"></span>
<span class="w">        </span><span class="p">}</span><span class="w"></span>
<span class="w">        </span><span class="k">return</span><span class="w"> </span><span class="kc">true</span><span class="w"></span>

<span class="w">    </span><span class="k">case</span><span class="w"> </span><span class="nx">reflect</span><span class="p">.</span><span class="nx">Map</span><span class="p">:</span><span class="w"></span>
<span class="w">        </span><span class="k">if</span><span class="w"> </span><span class="nx">x</span><span class="p">.</span><span class="nx">Len</span><span class="p">()</span><span class="w"> </span><span class="o">!=</span><span class="w"> </span><span class="nx">y</span><span class="p">.</span><span class="nx">Len</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">            </span><span class="k">return</span><span class="w"> </span><span class="kc">false</span><span class="w"></span>
<span class="w">        </span><span class="p">}</span><span class="w"></span>
<span class="w">        </span><span class="k">for</span><span class="w"> </span><span class="nx">_</span><span class="p">,</span><span class="w"> </span><span class="nx">k</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="k">range</span><span class="w"> </span><span class="nx">x</span><span class="p">.</span><span class="nx">MapKeys</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">            </span><span class="k">if</span><span class="w"> </span><span class="p">!</span><span class="nx">equal</span><span class="p">(</span><span class="nx">x</span><span class="p">.</span><span class="nx">MapIndex</span><span class="p">(</span><span class="nx">k</span><span class="p">),</span><span class="w"> </span><span class="nx">y</span><span class="p">.</span><span class="nx">MapIndex</span><span class="p">(</span><span class="nx">k</span><span class="p">),</span><span class="w"> </span><span class="nx">seen</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">                </span><span class="k">return</span><span class="w"> </span><span class="kc">false</span><span class="w"></span>
<span class="w">            </span><span class="p">}</span><span class="w"></span>
<span class="w">        </span><span class="p">}</span><span class="w"></span>
<span class="w">        </span><span class="k">return</span><span class="w"> </span><span class="kc">true</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"></span>
<span class="w">    </span><span class="nb">panic</span><span class="p">(</span><span class="s">&quot;unreachable&quot;</span><span class="p">)</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>

<span class="c1">// Equal 函数，检查x 和 y是否深度相等</span><span class="w"></span>
<span class="kd">func</span><span class="w"> </span><span class="nx">Equal</span><span class="p">(</span><span class="nx">x</span><span class="p">,</span><span class="w"> </span><span class="nx">y</span><span class="w"> </span><span class="kd">interface</span><span class="p">{})</span><span class="w"> </span><span class="kt">bool</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="nx">seen</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nb">make</span><span class="p">(</span><span class="kd">map</span><span class="p">[</span><span class="nx">comparison</span><span class="p">]</span><span class="kt">bool</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="k">return</span><span class="w"> </span><span class="nx">equal</span><span class="p">(</span><span class="nx">reflect</span><span class="p">.</span><span class="nx">ValueOf</span><span class="p">(</span><span class="nx">x</span><span class="p">),</span><span class="w"> </span><span class="nx">reflect</span><span class="p">.</span><span class="nx">ValueOf</span><span class="p">(</span><span class="nx">y</span><span class="p">),</span><span class="w"> </span><span class="nx">seen</span><span class="p">)</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>

<span class="kd">type</span><span class="w"> </span><span class="nx">comparison</span><span class="w"> </span><span class="kd">struct</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="nx">x</span><span class="p">,</span><span class="w"> </span><span class="nx">y</span><span class="w"> </span><span class="nx">unsafe</span><span class="p">.</span><span class="nx">Pointer</span><span class="w"></span>
<span class="w">    </span><span class="nx">t</span><span class="w">    </span><span class="nx">reflect</span><span class="p">.</span><span class="nx">Type</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>
</code></pre></div>

<p>在 API 中不暴露反射的细节，所以最后的可导出的 Equel 函数对参数显式调用 reflect.ValueOf 函数。  </p>
<h4 id="zhi-chi-xun-huan-yin-yong"><a class="toclink" href="#zhi-chi-xun-huan-yin-yong">支持循环引用</a></h4>
<p>为了确保算法终止设置可以对循环数据结果进行比较，它必须记录哪两对变量已经比较过了，并且避免再次进行比较。Equal 函数定义了一个叫做 comparison 的结构体集合，每个元素都包含两个变量的地址（unsafe.Pointer 表示）以及比较的类型。比如切片的比较，x 和 x[0] 的地址是一样的，这时候就要分开是两个切片的比较 x 和 y，还是切片的两个元素的比较 x[0] 和 y[0]。<br>
当 equal 确认了两个参数都是合法的并且类型也一样，在执行 switch 语句进行比较之前，先检查这两个变量是否已经比较过了，如果已经比较过了，则直接返回结果并终止这次递归比较。  </p>
<p><strong>unsafe.Pointer</strong><br>
就是上一节讲的问题，reflect.UnsafeAddr 返回的是一个 uintptr 类型（字母意思就是不安全的地址），这里需要直接转成 unsafe.Pointer 类型来保证地址可以始终指向最初的那个变量。  </p>
<h4 id="ce-shi-yan-zheng"><a class="toclink" href="#ce-shi-yan-zheng">测试验证</a></h4>
<p>下面输出完整的测试代码：</p>
<div class="highlight"><pre><span></span><code><span class="kn">package</span><span class="w"> </span><span class="nx">equal</span><span class="w"></span>

<span class="kn">import</span><span class="w"> </span><span class="p">(</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;bytes&quot;</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;fmt&quot;</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;testing&quot;</span><span class="w"></span>
<span class="p">)</span><span class="w"></span>

<span class="kd">func</span><span class="w"> </span><span class="nx">TestEqual</span><span class="p">(</span><span class="nx">t</span><span class="w"> </span><span class="o">*</span><span class="nx">testing</span><span class="p">.</span><span class="nx">T</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="nx">one</span><span class="p">,</span><span class="w"> </span><span class="nx">oneAgain</span><span class="p">,</span><span class="w"> </span><span class="nx">two</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="mi">1</span><span class="p">,</span><span class="w"> </span><span class="mi">1</span><span class="p">,</span><span class="w"> </span><span class="mi">2</span><span class="w"></span>

<span class="w">    </span><span class="kd">type</span><span class="w"> </span><span class="nx">CyclePtr</span><span class="w"> </span><span class="o">*</span><span class="nx">CyclePtr</span><span class="w"></span>
<span class="w">    </span><span class="kd">var</span><span class="w"> </span><span class="nx">cyclePtr1</span><span class="p">,</span><span class="w"> </span><span class="nx">cyclePtr2</span><span class="w"> </span><span class="nx">CyclePtr</span><span class="w"></span>
<span class="w">    </span><span class="nx">cyclePtr1</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="o">&amp;</span><span class="nx">cyclePtr1</span><span class="w"></span>
<span class="w">    </span><span class="nx">cyclePtr2</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="o">&amp;</span><span class="nx">cyclePtr2</span><span class="w"></span>

<span class="w">    </span><span class="kd">type</span><span class="w"> </span><span class="nx">CycleSlice</span><span class="w"> </span><span class="p">[]</span><span class="nx">CycleSlice</span><span class="w"></span>
<span class="w">    </span><span class="kd">var</span><span class="w"> </span><span class="nx">cycleSlice</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="nb">make</span><span class="p">(</span><span class="nx">CycleSlice</span><span class="p">,</span><span class="w"> </span><span class="mi">1</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="nx">cycleSlice</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="nx">cycleSlice</span><span class="w"></span>

<span class="w">    </span><span class="nx">ch1</span><span class="p">,</span><span class="w"> </span><span class="nx">ch2</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nb">make</span><span class="p">(</span><span class="kd">chan</span><span class="w"> </span><span class="kt">int</span><span class="p">),</span><span class="w"> </span><span class="nb">make</span><span class="p">(</span><span class="kd">chan</span><span class="w"> </span><span class="kt">int</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="kd">var</span><span class="w"> </span><span class="nx">ch1ro</span><span class="w"> </span><span class="o">&lt;-</span><span class="kd">chan</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="nx">ch1</span><span class="w"></span>

<span class="w">    </span><span class="kd">type</span><span class="w"> </span><span class="nx">mystring</span><span class="w"> </span><span class="kt">string</span><span class="w"></span>

<span class="w">    </span><span class="kd">var</span><span class="w"> </span><span class="nx">iface1</span><span class="p">,</span><span class="w"> </span><span class="nx">iface1Again</span><span class="p">,</span><span class="w"> </span><span class="nx">iface2</span><span class="w"> </span><span class="kd">interface</span><span class="p">{}</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="o">&amp;</span><span class="nx">one</span><span class="p">,</span><span class="w"> </span><span class="o">&amp;</span><span class="nx">oneAgain</span><span class="p">,</span><span class="w"> </span><span class="o">&amp;</span><span class="nx">two</span><span class="w"></span>

<span class="w">    </span><span class="k">for</span><span class="w"> </span><span class="nx">_</span><span class="p">,</span><span class="w"> </span><span class="nx">test</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="k">range</span><span class="w"> </span><span class="p">[]</span><span class="kd">struct</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="nx">x</span><span class="p">,</span><span class="w"> </span><span class="nx">y</span><span class="w"> </span><span class="kd">interface</span><span class="p">{}</span><span class="w"></span>
<span class="w">        </span><span class="nx">want</span><span class="w"> </span><span class="kt">bool</span><span class="w"></span>
<span class="w">    </span><span class="p">}{</span><span class="w"></span>
<span class="w">        </span><span class="c1">// basic types</span><span class="w"></span>
<span class="w">        </span><span class="p">{</span><span class="mi">1</span><span class="p">,</span><span class="w"> </span><span class="mi">1</span><span class="p">,</span><span class="w"> </span><span class="kc">true</span><span class="p">},</span><span class="w"></span>
<span class="w">        </span><span class="p">{</span><span class="mi">1</span><span class="p">,</span><span class="w"> </span><span class="mi">2</span><span class="p">,</span><span class="w"> </span><span class="kc">false</span><span class="p">},</span><span class="w">   </span><span class="c1">// different values</span><span class="w"></span>
<span class="w">        </span><span class="p">{</span><span class="mi">1</span><span class="p">,</span><span class="w"> </span><span class="mf">1.0</span><span class="p">,</span><span class="w"> </span><span class="kc">false</span><span class="p">},</span><span class="w"> </span><span class="c1">// different types</span><span class="w"></span>
<span class="w">        </span><span class="p">{</span><span class="s">&quot;foo&quot;</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;foo&quot;</span><span class="p">,</span><span class="w"> </span><span class="kc">true</span><span class="p">},</span><span class="w"></span>
<span class="w">        </span><span class="p">{</span><span class="s">&quot;foo&quot;</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;bar&quot;</span><span class="p">,</span><span class="w"> </span><span class="kc">false</span><span class="p">},</span><span class="w"></span>
<span class="w">        </span><span class="p">{</span><span class="nx">mystring</span><span class="p">(</span><span class="s">&quot;foo&quot;</span><span class="p">),</span><span class="w"> </span><span class="s">&quot;foo&quot;</span><span class="p">,</span><span class="w"> </span><span class="kc">false</span><span class="p">},</span><span class="w"> </span><span class="c1">// different types</span><span class="w"></span>
<span class="w">        </span><span class="c1">// slices</span><span class="w"></span>
<span class="w">        </span><span class="p">{[]</span><span class="kt">string</span><span class="p">{</span><span class="s">&quot;foo&quot;</span><span class="p">},</span><span class="w"> </span><span class="p">[]</span><span class="kt">string</span><span class="p">{</span><span class="s">&quot;foo&quot;</span><span class="p">},</span><span class="w"> </span><span class="kc">true</span><span class="p">},</span><span class="w"></span>
<span class="w">        </span><span class="p">{[]</span><span class="kt">string</span><span class="p">{</span><span class="s">&quot;foo&quot;</span><span class="p">},</span><span class="w"> </span><span class="p">[]</span><span class="kt">string</span><span class="p">{</span><span class="s">&quot;bar&quot;</span><span class="p">},</span><span class="w"> </span><span class="kc">false</span><span class="p">},</span><span class="w"></span>
<span class="w">        </span><span class="p">{[]</span><span class="kt">string</span><span class="p">{},</span><span class="w"> </span><span class="p">[]</span><span class="nb">string</span><span class="p">(</span><span class="kc">nil</span><span class="p">),</span><span class="w"> </span><span class="kc">true</span><span class="p">},</span><span class="w"></span>
<span class="w">        </span><span class="c1">// slice cycles</span><span class="w"></span>
<span class="w">        </span><span class="p">{</span><span class="nx">cycleSlice</span><span class="p">,</span><span class="w"> </span><span class="nx">cycleSlice</span><span class="p">,</span><span class="w"> </span><span class="kc">true</span><span class="p">},</span><span class="w"></span>
<span class="w">        </span><span class="c1">// maps</span><span class="w"></span>
<span class="w">        </span><span class="p">{</span><span class="w"></span>
<span class="w">            </span><span class="kd">map</span><span class="p">[</span><span class="kt">string</span><span class="p">][]</span><span class="kt">int</span><span class="p">{</span><span class="s">&quot;foo&quot;</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="mi">1</span><span class="p">,</span><span class="w"> </span><span class="mi">2</span><span class="p">,</span><span class="w"> </span><span class="mi">3</span><span class="p">}},</span><span class="w"></span>
<span class="w">            </span><span class="kd">map</span><span class="p">[</span><span class="kt">string</span><span class="p">][]</span><span class="kt">int</span><span class="p">{</span><span class="s">&quot;foo&quot;</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="mi">1</span><span class="p">,</span><span class="w"> </span><span class="mi">2</span><span class="p">,</span><span class="w"> </span><span class="mi">3</span><span class="p">}},</span><span class="w"></span>
<span class="w">            </span><span class="kc">true</span><span class="p">,</span><span class="w"></span>
<span class="w">        </span><span class="p">},</span><span class="w"></span>
<span class="w">        </span><span class="p">{</span><span class="w"></span>
<span class="w">            </span><span class="kd">map</span><span class="p">[</span><span class="kt">string</span><span class="p">][]</span><span class="kt">int</span><span class="p">{</span><span class="s">&quot;foo&quot;</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="mi">1</span><span class="p">,</span><span class="w"> </span><span class="mi">2</span><span class="p">,</span><span class="w"> </span><span class="mi">3</span><span class="p">}},</span><span class="w"></span>
<span class="w">            </span><span class="kd">map</span><span class="p">[</span><span class="kt">string</span><span class="p">][]</span><span class="kt">int</span><span class="p">{</span><span class="s">&quot;foo&quot;</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="mi">1</span><span class="p">,</span><span class="w"> </span><span class="mi">2</span><span class="p">,</span><span class="w"> </span><span class="mi">3</span><span class="p">,</span><span class="w"> </span><span class="mi">4</span><span class="p">}},</span><span class="w"></span>
<span class="w">            </span><span class="kc">false</span><span class="p">,</span><span class="w"></span>
<span class="w">        </span><span class="p">},</span><span class="w"></span>
<span class="w">        </span><span class="p">{</span><span class="w"></span>
<span class="w">            </span><span class="kd">map</span><span class="p">[</span><span class="kt">string</span><span class="p">][]</span><span class="kt">int</span><span class="p">{},</span><span class="w"></span>
<span class="w">            </span><span class="kd">map</span><span class="p">[</span><span class="kt">string</span><span class="p">][]</span><span class="nb">int</span><span class="p">(</span><span class="kc">nil</span><span class="p">),</span><span class="w"></span>
<span class="w">            </span><span class="kc">true</span><span class="p">,</span><span class="w"></span>
<span class="w">        </span><span class="p">},</span><span class="w"></span>
<span class="w">        </span><span class="c1">// pointers</span><span class="w"></span>
<span class="w">        </span><span class="p">{</span><span class="o">&amp;</span><span class="nx">one</span><span class="p">,</span><span class="w"> </span><span class="o">&amp;</span><span class="nx">one</span><span class="p">,</span><span class="w"> </span><span class="kc">true</span><span class="p">},</span><span class="w"></span>
<span class="w">        </span><span class="p">{</span><span class="o">&amp;</span><span class="nx">one</span><span class="p">,</span><span class="w"> </span><span class="o">&amp;</span><span class="nx">two</span><span class="p">,</span><span class="w"> </span><span class="kc">false</span><span class="p">},</span><span class="w"></span>
<span class="w">        </span><span class="p">{</span><span class="o">&amp;</span><span class="nx">one</span><span class="p">,</span><span class="w"> </span><span class="o">&amp;</span><span class="nx">oneAgain</span><span class="p">,</span><span class="w"> </span><span class="kc">true</span><span class="p">},</span><span class="w"></span>
<span class="w">        </span><span class="p">{</span><span class="nb">new</span><span class="p">(</span><span class="nx">bytes</span><span class="p">.</span><span class="nx">Buffer</span><span class="p">),</span><span class="w"> </span><span class="nb">new</span><span class="p">(</span><span class="nx">bytes</span><span class="p">.</span><span class="nx">Buffer</span><span class="p">),</span><span class="w"> </span><span class="kc">true</span><span class="p">},</span><span class="w"></span>
<span class="w">        </span><span class="c1">// pointer cycles</span><span class="w"></span>
<span class="w">        </span><span class="p">{</span><span class="nx">cyclePtr1</span><span class="p">,</span><span class="w"> </span><span class="nx">cyclePtr1</span><span class="p">,</span><span class="w"> </span><span class="kc">true</span><span class="p">},</span><span class="w"></span>
<span class="w">        </span><span class="p">{</span><span class="nx">cyclePtr2</span><span class="p">,</span><span class="w"> </span><span class="nx">cyclePtr2</span><span class="p">,</span><span class="w"> </span><span class="kc">true</span><span class="p">},</span><span class="w"></span>
<span class="w">        </span><span class="p">{</span><span class="nx">cyclePtr1</span><span class="p">,</span><span class="w"> </span><span class="nx">cyclePtr2</span><span class="p">,</span><span class="w"> </span><span class="kc">true</span><span class="p">},</span><span class="w"> </span><span class="c1">// they&#39;re deeply equal</span><span class="w"></span>
<span class="w">        </span><span class="c1">// functions</span><span class="w"></span>
<span class="w">        </span><span class="p">{(</span><span class="kd">func</span><span class="p">())(</span><span class="kc">nil</span><span class="p">),</span><span class="w"> </span><span class="p">(</span><span class="kd">func</span><span class="p">())(</span><span class="kc">nil</span><span class="p">),</span><span class="w"> </span><span class="kc">true</span><span class="p">},</span><span class="w"></span>
<span class="w">        </span><span class="p">{(</span><span class="kd">func</span><span class="p">())(</span><span class="kc">nil</span><span class="p">),</span><span class="w"> </span><span class="kd">func</span><span class="p">()</span><span class="w"> </span><span class="p">{},</span><span class="w"> </span><span class="kc">false</span><span class="p">},</span><span class="w"></span>
<span class="w">        </span><span class="p">{</span><span class="kd">func</span><span class="p">()</span><span class="w"> </span><span class="p">{},</span><span class="w"> </span><span class="kd">func</span><span class="p">()</span><span class="w"> </span><span class="p">{},</span><span class="w"> </span><span class="kc">false</span><span class="p">},</span><span class="w"></span>
<span class="w">        </span><span class="c1">// arrays</span><span class="w"></span>
<span class="w">        </span><span class="p">{[</span><span class="o">...</span><span class="p">]</span><span class="kt">int</span><span class="p">{</span><span class="mi">1</span><span class="p">,</span><span class="w"> </span><span class="mi">2</span><span class="p">,</span><span class="w"> </span><span class="mi">3</span><span class="p">},</span><span class="w"> </span><span class="p">[</span><span class="o">...</span><span class="p">]</span><span class="kt">int</span><span class="p">{</span><span class="mi">1</span><span class="p">,</span><span class="w"> </span><span class="mi">2</span><span class="p">,</span><span class="w"> </span><span class="mi">3</span><span class="p">},</span><span class="w"> </span><span class="kc">true</span><span class="p">},</span><span class="w"></span>
<span class="w">        </span><span class="p">{[</span><span class="o">...</span><span class="p">]</span><span class="kt">int</span><span class="p">{</span><span class="mi">1</span><span class="p">,</span><span class="w"> </span><span class="mi">2</span><span class="p">,</span><span class="w"> </span><span class="mi">3</span><span class="p">},</span><span class="w"> </span><span class="p">[</span><span class="o">...</span><span class="p">]</span><span class="kt">int</span><span class="p">{</span><span class="mi">1</span><span class="p">,</span><span class="w"> </span><span class="mi">2</span><span class="p">,</span><span class="w"> </span><span class="mi">4</span><span class="p">},</span><span class="w"> </span><span class="kc">false</span><span class="p">},</span><span class="w"></span>
<span class="w">        </span><span class="c1">// channels</span><span class="w"></span>
<span class="w">        </span><span class="p">{</span><span class="nx">ch1</span><span class="p">,</span><span class="w"> </span><span class="nx">ch1</span><span class="p">,</span><span class="w"> </span><span class="kc">true</span><span class="p">},</span><span class="w"></span>
<span class="w">        </span><span class="p">{</span><span class="nx">ch1</span><span class="p">,</span><span class="w"> </span><span class="nx">ch2</span><span class="p">,</span><span class="w"> </span><span class="kc">false</span><span class="p">},</span><span class="w"></span>
<span class="w">        </span><span class="p">{</span><span class="nx">ch1ro</span><span class="p">,</span><span class="w"> </span><span class="nx">ch1</span><span class="p">,</span><span class="w"> </span><span class="kc">false</span><span class="p">},</span><span class="w"> </span><span class="c1">// NOTE: not equal</span><span class="w"></span>
<span class="w">        </span><span class="c1">// interfaces</span><span class="w"></span>
<span class="w">        </span><span class="p">{</span><span class="o">&amp;</span><span class="nx">iface1</span><span class="p">,</span><span class="w"> </span><span class="o">&amp;</span><span class="nx">iface1</span><span class="p">,</span><span class="w"> </span><span class="kc">true</span><span class="p">},</span><span class="w"></span>
<span class="w">        </span><span class="p">{</span><span class="o">&amp;</span><span class="nx">iface1</span><span class="p">,</span><span class="w"> </span><span class="o">&amp;</span><span class="nx">iface2</span><span class="p">,</span><span class="w"> </span><span class="kc">false</span><span class="p">},</span><span class="w"></span>
<span class="w">        </span><span class="p">{</span><span class="o">&amp;</span><span class="nx">iface1Again</span><span class="p">,</span><span class="w"> </span><span class="o">&amp;</span><span class="nx">iface1</span><span class="p">,</span><span class="w"> </span><span class="kc">true</span><span class="p">},</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="k">if</span><span class="w"> </span><span class="nx">Equal</span><span class="p">(</span><span class="nx">test</span><span class="p">.</span><span class="nx">x</span><span class="p">,</span><span class="w"> </span><span class="nx">test</span><span class="p">.</span><span class="nx">y</span><span class="p">)</span><span class="w"> </span><span class="o">!=</span><span class="w"> </span><span class="nx">test</span><span class="p">.</span><span class="nx">want</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">            </span><span class="nx">t</span><span class="p">.</span><span class="nx">Errorf</span><span class="p">(</span><span class="s">&quot;Equal(%v, %v) = %t&quot;</span><span class="p">,</span><span class="w"></span>
<span class="w">                </span><span class="nx">test</span><span class="p">.</span><span class="nx">x</span><span class="p">,</span><span class="w"> </span><span class="nx">test</span><span class="p">.</span><span class="nx">y</span><span class="p">,</span><span class="w"> </span><span class="p">!</span><span class="nx">test</span><span class="p">.</span><span class="nx">want</span><span class="p">)</span><span class="w"></span>
<span class="w">        </span><span class="p">}</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>

<span class="kd">func</span><span class="w"> </span><span class="nx">Example_equal</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="nx">fmt</span><span class="p">.</span><span class="nx">Println</span><span class="p">(</span><span class="nx">Equal</span><span class="p">([]</span><span class="kt">int</span><span class="p">{</span><span class="mi">1</span><span class="p">,</span><span class="w"> </span><span class="mi">2</span><span class="p">,</span><span class="w"> </span><span class="mi">3</span><span class="p">},</span><span class="w"> </span><span class="p">[]</span><span class="kt">int</span><span class="p">{</span><span class="mi">1</span><span class="p">,</span><span class="w"> </span><span class="mi">2</span><span class="p">,</span><span class="w"> </span><span class="mi">3</span><span class="p">}))</span><span class="w">        </span><span class="c1">// &quot;true&quot;</span><span class="w"></span>
<span class="w">    </span><span class="nx">fmt</span><span class="p">.</span><span class="nx">Println</span><span class="p">(</span><span class="nx">Equal</span><span class="p">([]</span><span class="kt">string</span><span class="p">{</span><span class="s">&quot;foo&quot;</span><span class="p">},</span><span class="w"> </span><span class="p">[]</span><span class="kt">string</span><span class="p">{</span><span class="s">&quot;bar&quot;</span><span class="p">}))</span><span class="w">      </span><span class="c1">// &quot;false&quot;</span><span class="w"></span>
<span class="w">    </span><span class="nx">fmt</span><span class="p">.</span><span class="nx">Println</span><span class="p">(</span><span class="nx">Equal</span><span class="p">([]</span><span class="nb">string</span><span class="p">(</span><span class="kc">nil</span><span class="p">),</span><span class="w"> </span><span class="p">[]</span><span class="kt">string</span><span class="p">{}))</span><span class="w">             </span><span class="c1">// &quot;true&quot;</span><span class="w"></span>
<span class="w">    </span><span class="nx">fmt</span><span class="p">.</span><span class="nx">Println</span><span class="p">(</span><span class="nx">Equal</span><span class="p">(</span><span class="kd">map</span><span class="p">[</span><span class="kt">string</span><span class="p">]</span><span class="nb">int</span><span class="p">(</span><span class="kc">nil</span><span class="p">),</span><span class="w"> </span><span class="kd">map</span><span class="p">[</span><span class="kt">string</span><span class="p">]</span><span class="kt">int</span><span class="p">{}))</span><span class="w"> </span><span class="c1">// &quot;true&quot;</span><span class="w"></span>
<span class="w">    </span><span class="c1">// Output:</span><span class="w"></span>
<span class="w">    </span><span class="c1">// true</span><span class="w"></span>
<span class="w">    </span><span class="c1">// false</span><span class="w"></span>
<span class="w">    </span><span class="c1">// true</span><span class="w"></span>
<span class="w">    </span><span class="c1">// true</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>

<span class="kd">func</span><span class="w"> </span><span class="nx">Example_equalCycle</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="c1">// Circular linked lists a -&gt; b -&gt; a and c -&gt; c.</span><span class="w"></span>
<span class="w">    </span><span class="kd">type</span><span class="w"> </span><span class="nx">link</span><span class="w"> </span><span class="kd">struct</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="nx">value</span><span class="w"> </span><span class="kt">string</span><span class="w"></span>
<span class="w">        </span><span class="nx">tail</span><span class="w">  </span><span class="o">*</span><span class="nx">link</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"></span>
<span class="w">    </span><span class="nx">a</span><span class="p">,</span><span class="w"> </span><span class="nx">b</span><span class="p">,</span><span class="w"> </span><span class="nx">c</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="o">&amp;</span><span class="nx">link</span><span class="p">{</span><span class="nx">value</span><span class="p">:</span><span class="w"> </span><span class="s">&quot;a&quot;</span><span class="p">},</span><span class="w"> </span><span class="o">&amp;</span><span class="nx">link</span><span class="p">{</span><span class="nx">value</span><span class="p">:</span><span class="w"> </span><span class="s">&quot;b&quot;</span><span class="p">},</span><span class="w"> </span><span class="o">&amp;</span><span class="nx">link</span><span class="p">{</span><span class="nx">value</span><span class="p">:</span><span class="w"> </span><span class="s">&quot;c&quot;</span><span class="p">}</span><span class="w"></span>
<span class="w">    </span><span class="nx">a</span><span class="p">.</span><span class="nx">tail</span><span class="p">,</span><span class="w"> </span><span class="nx">b</span><span class="p">.</span><span class="nx">tail</span><span class="p">,</span><span class="w"> </span><span class="nx">c</span><span class="p">.</span><span class="nx">tail</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="nx">b</span><span class="p">,</span><span class="w"> </span><span class="nx">a</span><span class="p">,</span><span class="w"> </span><span class="nx">c</span><span class="w"></span>
<span class="w">    </span><span class="nx">fmt</span><span class="p">.</span><span class="nx">Println</span><span class="p">(</span><span class="nx">Equal</span><span class="p">(</span><span class="nx">a</span><span class="p">,</span><span class="w"> </span><span class="nx">a</span><span class="p">))</span><span class="w"> </span><span class="c1">// &quot;true&quot;</span><span class="w"></span>
<span class="w">    </span><span class="nx">fmt</span><span class="p">.</span><span class="nx">Println</span><span class="p">(</span><span class="nx">Equal</span><span class="p">(</span><span class="nx">b</span><span class="p">,</span><span class="w"> </span><span class="nx">b</span><span class="p">))</span><span class="w"> </span><span class="c1">// &quot;true&quot;</span><span class="w"></span>
<span class="w">    </span><span class="nx">fmt</span><span class="p">.</span><span class="nx">Println</span><span class="p">(</span><span class="nx">Equal</span><span class="p">(</span><span class="nx">c</span><span class="p">,</span><span class="w"> </span><span class="nx">c</span><span class="p">))</span><span class="w"> </span><span class="c1">// &quot;true&quot;</span><span class="w"></span>
<span class="w">    </span><span class="nx">fmt</span><span class="p">.</span><span class="nx">Println</span><span class="p">(</span><span class="nx">Equal</span><span class="p">(</span><span class="nx">a</span><span class="p">,</span><span class="w"> </span><span class="nx">b</span><span class="p">))</span><span class="w"> </span><span class="c1">// &quot;false&quot;</span><span class="w"></span>
<span class="w">    </span><span class="nx">fmt</span><span class="p">.</span><span class="nx">Println</span><span class="p">(</span><span class="nx">Equal</span><span class="p">(</span><span class="nx">a</span><span class="p">,</span><span class="w"> </span><span class="nx">c</span><span class="p">))</span><span class="w"> </span><span class="c1">// &quot;false&quot;</span><span class="w"></span>
<span class="w">    </span><span class="c1">// Output:</span><span class="w"></span>
<span class="w">    </span><span class="c1">// true</span><span class="w"></span>
<span class="w">    </span><span class="c1">// true</span><span class="w"></span>
<span class="w">    </span><span class="c1">// true</span><span class="w"></span>
<span class="w">    </span><span class="c1">// false</span><span class="w"></span>
<span class="w">    </span><span class="c1">// false</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>
</code></pre></div>

<p>在最后的示例测试函数 Example_equalCycle 中，验证了一个循环链表也能完成比较，而不会卡住：</p>
<div class="highlight"><pre><span></span><code><span class="kd">type</span><span class="w"> </span><span class="nx">link</span><span class="w"> </span><span class="kd">struct</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="nx">value</span><span class="w"> </span><span class="kt">string</span><span class="w"></span>
<span class="w">    </span><span class="nx">tail</span><span class="w">  </span><span class="o">*</span><span class="nx">link</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>
<span class="nx">a</span><span class="p">,</span><span class="w"> </span><span class="nx">b</span><span class="p">,</span><span class="w"> </span><span class="nx">c</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="o">&amp;</span><span class="nx">link</span><span class="p">{</span><span class="nx">value</span><span class="p">:</span><span class="w"> </span><span class="s">&quot;a&quot;</span><span class="p">},</span><span class="w"> </span><span class="o">&amp;</span><span class="nx">link</span><span class="p">{</span><span class="nx">value</span><span class="p">:</span><span class="w"> </span><span class="s">&quot;b&quot;</span><span class="p">},</span><span class="w"> </span><span class="o">&amp;</span><span class="nx">link</span><span class="p">{</span><span class="nx">value</span><span class="p">:</span><span class="w"> </span><span class="s">&quot;c&quot;</span><span class="p">}</span><span class="w"></span>
<span class="nx">a</span><span class="p">.</span><span class="nx">tail</span><span class="p">,</span><span class="w"> </span><span class="nx">b</span><span class="p">.</span><span class="nx">tail</span><span class="p">,</span><span class="w"> </span><span class="nx">c</span><span class="p">.</span><span class="nx">tail</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="nx">b</span><span class="p">,</span><span class="w"> </span><span class="nx">a</span><span class="p">,</span><span class="w"> </span><span class="nx">c</span><span class="w"></span>
</code></pre></div>

<h3 id="guan-yu-an-quan-de-zhu-yi-shi-xiang"><a class="toclink" href="#guan-yu-an-quan-de-zhu-yi-shi-xiang">关于安全的注意事项</a></h3>
<p>高级语言将程序、程序员和神秘的机器指令集隔离开来，并且也隔离了诸如变量在内存中的存储位置，数据类型的大小，数据结构的内存布局，以及关于机器的其他实现细节。因为有这个隔离层的存在，我们可以编写安全健壮的代码并且不加改动就可以在任何操作系统上运行。<br>
但 unsafe 包可以让程序穿透这层隔离去使用一些关键的但通过其他方式无法使用到的特性，或者是为了实现更高的性能。付出的代价通常就是程序的可移植性和安全性，所以当你使用 unsafe 的时候就得自己承担风险。大多数情况都不需要甚至永远不需要使用 unsafe 包。当然，偶尔还是会遇到一些使用的场景，其中一些关键代码最好还是通过 unsafe 来写。如果用了，那就要确保尽可能地限制在小范围内使用，这样大多数的程序就不会受到这个影响。  </p>
      </div>
      <div class="back-to-top">
        <a href="/">HOME</a>
        <a href="#top">TOP</a>
      </div>
    </article>
  </div>
<!-- end article -->
<!-- 页面往下滚动一段之后才会显示TOC -->
<script>
  window.onscroll = function() {
    var tocbox = document.getElementsByClassName('toc')[0];
    var osTop = document.documentElement.scrollTop || document.body.scrollTop;
    var osWidth = document.documentElement.scrollWidth || document.body.scrollWidth;
    // console.log(osTop)
    if (osTop>300 && osWidth>865) {
      tocbox.style.display = "block"
    }
    if (osTop<300 || osWidth<865) {
      tocbox.style.display = "none"
    }
  }
</script>
                <footer>
                    <div class="icons">
                    </div>
                    <span id="busuanzi_container_page_pv" style="padding: 10px">本文阅读量<span id="busuanzi_value_page_pv"></span>次</span>
                    <span id="busuanzi_container_site_pv" style="padding: 10px">本站总访问量<span id="busuanzi_value_site_pv"></span>次</span>
                    <span id="busuanzi_container_site_uv" style="padding: 10px">本站总访客数<span id="busuanzi_value_site_uv"></span>人</span>
                    <p>© <script>document.write(moment().format('YYYY'));</script> 749B</p>
                </footer>
        </div>
</body>
</html>